package com.lap.dev.starter.autoconfigure.properties;

import com.lap.dev.starter.core.CustomLoadBalancer;
import com.lap.dev.starter.shared.NetworkUtil;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;

@Slf4j
public class LoadBalancerConfig {

  @Profile({"dev", "local"})
  @Bean
  @Primary
  public ReactorServiceInstanceLoadBalancer customLoadBalancer(
      Environment environment, ObjectProvider<ServiceInstanceListSupplier> suppliers) {
    String serviceId = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
    Set<String> allIpSet = NetworkUtil.getAvailableIPv4Addresses();
    log.info("【如果非开发环境初始化这个负载，请注意删除】初始化自定义负载器 :{},本机的ip:{}", serviceId, allIpSet);
    return new CustomLoadBalancer(serviceId, suppliers, allIpSet);
  }
}
